package db;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
import beans.DBConfiguration;

public class DBManager {

	private static DBConfiguration dbConfig;
	static{
		Properties pro = new Properties();
		try {
			pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		dbConfig = new DBConfiguration();
		dbConfig.setDriver(pro.getProperty("driver"));
		dbConfig.setPassword(pro.getProperty("password"));
		dbConfig.setUrl(pro.getProperty("url"));
		dbConfig.setUser(pro.getProperty("user"));
		dbConfig.setUsingDB(pro.getProperty("usingDB"));
	}

	/**
	 * 获取数据库连接
	 * @return
	 */
	public static Connection getConnection(){
		try {
			Class.forName(dbConfig.getDriver());
			return DriverManager.getConnection(dbConfig.getUrl(), dbConfig.getUser(), dbConfig.getPassword());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	/**
	 * 关闭数据库连接
	 * @param conn 数据库连接
	 * @param statement 
	 * @param prepStatement
	 * @param rs
	 */
	public static void closeConnection(Connection conn, Statement statement, PreparedStatement prepStatement,
			ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (statement != null) {
				statement.close();
			}
			if (prepStatement != null) {
				prepStatement.close();
			}
			if(conn!=null){
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

